﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartSpace.News
{
    public class NewsDbContext : DbContext
    {
        public NewsDbContext()
            : base("name=smartspace")
        {
            if (SmartSpace.Configuration.IsAutomaticMigrations)
            {
                Database.SetInitializer<NewsDbContext>(new MigrateDatabaseToLatestVersion<NewsDbContext, DBMC>());
            }
            else
            {
                Database.SetInitializer<NewsDbContext>(null);
            }
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Article>().ToTable("news_article");
            modelBuilder.Entity<Article>().HasKey(p => p.Id);

            modelBuilder.Entity<Category>().ToTable("news_category");
            modelBuilder.Entity<Category>().HasKey(p => p.Id);

            base.OnModelCreating(modelBuilder);
        }
    }

    internal sealed class DBMC : DbMigrationsConfiguration<NewsDbContext>
    {
        public DBMC()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }
    }

    public sealed class AutomaticDbMigrationsConfiguration<TContext> : DbMigrationsConfiguration<TContext> where TContext : System.Data.Entity.DbContext
    {
        public AutomaticDbMigrationsConfiguration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }
    }
}
